package com.tg.app.util;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tg.app.activity.tools.DevToolsActivity;
import com.tg.app.camera.Camera;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.data.bean.DeviceSettingsInfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LocalVideoDataUtil {

    private static final String TAG = "LocalVideoDataUtil";

    private DeviceSettingsInfo deviceSettingsInfo;
    private Camera camera;
    private Handler handler = new Handler(Looper.getMainLooper());

    private String localVideoDataFileName = null;
    private File localVideoDataFile = null;

    public LocalVideoDataUtil(DeviceSettingsInfo deviceSettingsInfo, Camera camera) {
        this.camera = camera;
        this.deviceSettingsInfo = deviceSettingsInfo;
    }

    public void append(byte[] data) {

        if (!DevToolsActivity.enableWriteVideoDataToLocalFile) {
            return;
        }

        if (localVideoDataFileName == null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String t =format.format(new Date());

            String name = deviceSettingsInfo.uuid;
            if (!TextUtils.isEmpty(camera.deviceName)) {
                name = camera.deviceName;
            }

            localVideoDataFileName = name + "-" + t + ".h264";

            String localFolderPath = Environment.getExternalStorageDirectory().getPath() + "/iCam-Local";
            File dir = new File(localFolderPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            localVideoDataFile = new File(dir, localVideoDataFileName);

            if (localVideoDataFile.exists()) {
                localVideoDataFile.delete();
            }

            handler.post(() -> Toast.makeText(TGApplicationBase.getApplicationContext(), "视频数据将会保存在: " + localVideoDataFile.getAbsolutePath(), Toast.LENGTH_LONG).show());
        }

        try {
            Log.i(TAG, "append: path = " + localVideoDataFile.getAbsolutePath());
            Log.i(TAG, "append:    before.length = " + localVideoDataFile.length());
            Log.i(TAG, "append:    data.length = " + data.length);
            OutputStream os = new FileOutputStream(localVideoDataFile, true);
            os.write(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
}
